# -*- coding: UTF-8 -*-
import json
from flask import Flask, request, jsonify
from flask_cors import *
import pymysql
connect = pymysql.Connect(
    host='localhost',
    port=3306,
    user='root',
    passwd='your password',
    db='test',#数据库库名
    charset='gbk'#字符集类型,须一致
)


app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route('/plan', methods=["GET"])
def calculate():
    cursor = connect.cursor()
    sql = "SELECT * FROM `splan` ORDER BY date desc LIMIT 20"
    connect.ping(reconnect=True)  # keep connect, avoid “raise err.InterfaceError("(0, '')")”
    cursor.execute(sql)
    results = cursor.fetchall()
    if connect:
        connect.close()
    if cursor:
        cursor.close()
    items = []
    data = {}
    for r in results:
        item = {'date': r[1], 'username': r[2], 'plan': r[3]}
        items.append(item)
    data['items'] = items
    data = json.dumps(data, default=str, ensure_ascii=False)
    # 把data再次转为json类型即可
    data = json.loads(data)
    print(data)
    return data
	
@app.route('/submit', methods=["post"])
def submit():
	params = request.form if request.form else request.json
	username = params.get("username", 0)
	plan = params.get("plan",0)
	date = params.get("date",0)
	print(username)
	print(plan)
	print(date)
	cursor = connect.cursor()
	sql = "INSERT INTO splan(date,username,plan) VALUES ('%s','%s','%s')"
	data = (date,username,plan)
	connect.ping(reconnect=True)  # keep connect, avoid “raise err.InterfaceError("(0, '')")”
	cursor.execute(sql % data)
	connect.commit()
	if connect:
		connect.close()
	if cursor:
		cursor.close()
	res = {"result": 1}
	return jsonify(res)


if __name__ == '__main__':
    app.run(host='0.0.0.0', threaded=True, debug=True, port=8080)
